//
//  LoginViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/1/23.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "LoginViewController.h"
#import "RegistOneViewController.h"
#import "MyNavigationViewController.h"
@interface LoginViewController ()<UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UIButton *loginButton;
@property (strong, nonatomic) IBOutlet UITextField *personIdField;
@property (strong, nonatomic) IBOutlet UITextField *personPassField;

@end

@implementation LoginViewController

- (void)viewWillAppear:(BOOL)animated{
    if (_ifRegister) {
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
        RegistOneViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"RegistOne"];
        page.pageFinishBlock = ^(NSString *str){
            [self dismissViewControllerAnimated:NO completion:^{}];
        };
        [self presentViewController:page animated:YES completion:^{}];
        _ifRegister = NO;
    }

}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initViewLayout];
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    self.loginButton.layer.cornerRadius = 20*VerticalRatio();
    

}

#pragma mark === 取消登陆
- (IBAction)cancelLogin:(id)sender {
    
    MyNavigationViewController * navC = (MyNavigationViewController *)self.navigationController;
    [navC popViewController];
}
#pragma mark === 登陆
- (IBAction)loginHandel:(id)sender {
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"appUserLogin" forKey:@"method"];
    [dic setObject:_personIdField.text forKey:@"userName"];
    [dic setObject:[Common shaEncrypt:_personPassField.text] forKey:@"password"];
    NSString *identifierForVendor = [[UIDevice currentDevice].identifierForVendor UUIDString];
    [dic setObject:identifierForVendor forKey:@"deviceIdentity"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_UserLogin withHttpType:@"POST" withTag:SX_SubmitLoginDataTag];
    
    _personPassField.delegate = self;
    
}
#pragma mark === 忘记密码
- (IBAction)forgetPasswordHandel:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    RegistOneViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ForgetPassword"];
    page.pageFinishBlock = ^(NSString *str){
        MyNavigationViewController * navC = (MyNavigationViewController *)self.navigationController;
        [navC popViewController];
    };
    MyNavigationViewController * navC = (MyNavigationViewController *)self.navigationController;
    [navC pushToViewController:page ];
}
#pragma mark === 注册
- (IBAction)registHandel:(id)sender {

        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
        RegistOneViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"RegistOne"];
       page.pageFinishBlock = ^(NSString *str){
           MyNavigationViewController * navC = (MyNavigationViewController *)self.navigationController;
           [navC popViewController];
       };
    MyNavigationViewController * navC = (MyNavigationViewController *)self.navigationController;
    [navC pushToViewController:page ];
  
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isEqualToString:@"\n"]) {
        NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
        [dic setObject:@"appUserLogin" forKey:@"method"];
        [dic setObject:_personIdField.text forKey:@"userName"];
        [dic setObject:[Common shaEncrypt:_personPassField.text] forKey:@"password"];
        NSString *identifierForVendor = [[UIDevice currentDevice].identifierForVendor UUIDString];
        [dic setObject:identifierForVendor forKey:@"deviceIdentity"];
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:SX_UserLogin withHttpType:@"POST" withTag:SX_SubmitLoginDataTag];
        return NO;
    }
    return YES;
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    
    
    if (tag==SX_SubmitLoginDataTag) {
        
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            
            //1. 创建一个plist文件
            NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
            NSString *path=[paths    objectAtIndex:0];
            NSString *filename=[path stringByAppendingPathComponent:@"myUserInfo.plist"];
            
            NSFileManager* fm = [NSFileManager defaultManager];
            [fm createFileAtPath:filename contents:nil attributes:nil];
            NSMutableDictionary *dic = database[@"result"];
            NSMutableDictionary * dict = dic[@"sysUser"];
            NSDictionary *userinfoDic = @{Key_User_nickname:[self dataIsNull:dict dataStr:@"suseLoginName"],
                                          Key_User_password:[self dataIsNull:dic dataStr:@"susePassword"],
                                          Key_User_userId:[self dataIsNull:dict dataStr:@"suseId"],
                                          Key_User_userPhone:self.personIdField.text,
                                          Key_User_museBirthday:[self dataIsNull:dic dataStr:@"museBirthday"],
                                          Key_User_museIntegration:[self dataIsNull:dic dataStr:@"museIntegration"],
                                          Key_User_head:@"",
                                          Key_User_museRegisterDate:[self dataIsNull:dic dataStr:@"museRegisterDate"],
                                          Key_User_suseType:[self dataIsNull:dict dataStr:@"suseType"],
                                          Key_User_suseIdDelete:[self dataIsNull:dic dataStr:@"suseIdDelete"]
                                          };
            [userinfoDic writeToFile:filename atomically:YES];
            [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"ifLogin"];
            
            MyNavigationViewController * navC = (MyNavigationViewController *)self.navigationController;
            [navC popViewController];
            
                if(self.pageFinishBlock)
                self.pageFinishBlock();
        
        }
        
    }
}


//判断数据是否存在
- (NSString *)dataIsNull:(NSDictionary *)dic dataStr:(NSString *)dataStr{
    if (!dic[dataStr]) {
        return @"";
    }else{
        return dic[dataStr];
    }
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
